# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：   aes8
   Author :      wuqianyong
   date：        2019/3/18
-------------------------------------------------
   Change Activity:
                   2017/4/1:
-------------------------------------------------
Description :
 

"""
__author__ = 'wuqianyong'
import base64
import sys
from Crypto.Cipher import AES
import binascii
import hashlib
import re
import time
BS = AES.block_size


def padding_pkcs5(value):
    en_value = str.encode(value)
    return en_value + str.encode((BS - len(en_value) % BS) * chr(BS - len(value) % BS))


def padding_zero(value):
    while len(value) % 16 != 0:
        value += '\0'
    return str.encode(value)


def aes_ecb_encrypt(key, value):
    # AES/ECB/PKCS5padding
    # key is sha1prng encrypted before
    cryptor = AES.new(bytes.fromhex(key), AES.MODE_ECB)
    padding_value = padding_pkcs5(value)  # padding content with pkcs5
    # print(padding_value)
    ciphertext = cryptor.encrypt(padding_value)
    encrypted_text = base64.b64encode(ciphertext)
    return encrypted_text
    # return ''.join(['%02x' % i for i in ciphertext]).upper()


def get_sha1prng_key(key):
    '''[summary]
    encrypt key with SHA1PRNG
    same as java AES crypto key generator SHA1PRNG
    Arguments:
        key {[string]} -- [key]

    Returns:
        [string] -- [hexstring]
    '''
    signature = hashlib.sha1(key.encode()).digest()
    signature = hashlib.sha1(signature).digest()
    return ''.join(['%02x' % i for i in signature]).upper()[:32]


def aes_ecb_decrypt(key: str, value: str) -> str:
    ''' AES/ECB/NoPadding decrypt '''
    key = bytes.fromhex(key)
    cryptor = AES.new(key, AES.MODE_ECB)
    decr_value = base64.b64decode(value)
    ciphertext = cryptor.decrypt(decr_value)
    # print(ciphertext)
    return clean_end(ciphertext)


def clean_end(de_text: bytes) -> str:
    """
    清理 结尾的乱码
    :param de_text:
    :return:
    """
    de_text = str(de_text, encoding='utf-8', errors='replace')
    # print(de_text)
    chr_list = [chr(x) for x in range(1, BS)]
    for i in range(len(de_text) - 1, 0, -1):
        if de_text[i] not in chr_list:
            break
    return de_text[:i + 1]
if __name__ == '__main__':

    # key = 'zheshiyige'
    key = 'QAZOKMXCVBNZAZY1311ERTHJK'

    text = '{}'.format(int(time.time()))
    print(text)
    aes128string = aes_ecb_encrypt(get_sha1prng_key(key), text)
    print(str(aes128string,encoding='utf-8'))
    aes128string = '0qOsyShqy9rbFK6DMI5rww=='
    key = 'QAZOKMXCVBNZAZY1311ERTHJK'
    de_text = aes_ecb_decrypt(get_sha1prng_key(key), aes128string)

    print(de_text)
    print(type(de_text))

    # print(str(bytes.fromhex(de_text)))
    # print(len(str(de_text, encoding='utf-8').rstrip('\0')))
    # print(data.encode('utf-8').hex())
    # print(len(data.encode('utf-8').hex()))
    # if __name__ == '__main__':
    #     pass
